import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:bruno/bruno.dart';
import 'package:image_picker/image_picker.dart';
import 'package:intl/intl.dart';
import 'package:sph_driver/Authentication/DriverCard.dart';

import '../AppConfig/Config.dart';
import '../AppConfig/LocalStorage.dart';
import '../AppConfig/RouteAct.dart';
import '../Main/EditInformation/EditIDCard.dart';
import '../http/api.dart';
import '../l10n/messages.dart';
import 'package:image/image.dart' as img;

import 'FaceCheck.dart';
import 'FaceCheckView.dart';
class IDCardVC extends StatefulWidget {
  const IDCardVC({super.key, required this.token});
  final String token;
  @override
  State<IDCardVC> createState() => _IDCardVCState();
}

class _IDCardVCState extends State<IDCardVC> {
  List titleList=["姓名","身份证","住址","起始日期","到期日期"];
  List dataList =["","","","",""];
  String? name;
  String? IDCard;
  String? address;
  String? endTime;
  late String ChooseIndex="1";
  final ImagePicker picker = new ImagePicker();
//用户本地图片
  File? _userImage;
  File? _userImage2;//存放获取到的本地路径
  int oneCheck =0;
  String cardImgStr="";
  String cardImgStr2="";
  TextEditingController _nametextEditingController = TextEditingController();
  Map dataMap={};
  String getfrontPath="";
  String getbackPath="";
  String faceUrl="";
  String verufyToken="";


  void uploadOcrAction() async {
    ApiManager.postData(
      context,
      'api/system/dev/ocr/doOcr',
      {
        "type": "DID",
        "frontFileFormat": "jpg",
        "frontData": cardImgStr,
        "backFileFormat":"jpg",
        "backData":cardImgStr2,
      },
          (responseData) {
        BrnToast.show("识别成功", context, duration: BrnDuration.short,);
        dataMap=responseData['data']['result'];
        setState(() {
          dataList=[dataMap['name'],dataMap['idcard'],dataMap['address'],dataMap['validFrom'],dataMap['validTo']];
          // oneCheck==1?
          getfrontPath=responseData['data']['frontPath'];
          getbackPath=responseData['data']['backPath'];
        });
      },
    );
  }
  void uploadBackOcrAction()  async{
    print("cardImgStr:$cardImgStr");
    print("cardImgStr2:$cardImgStr2");
    String? token = await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) async {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header+'api/system/dev/ocr/doOcr',
      data: {
        "type": "DID",
        "frontFileFormat":"JPG",
        "frontData": cardImgStr,
        "backFileFormat": "JPG",
        "backData": cardImgStr2,
      }
      ,
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),

    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          print("code：$code");
          BrnToast.show("识别成功", context, duration: BrnDuration.short,);
          dataMap=jsonMap['data']['result'];
          setState(() {
            dataList=[dataMap['name'],dataMap['idcard'],dataMap['address'],dataMap['validFrom'],dataMap['validTo']];
            getfrontPath=jsonMap['data']['frontPath'];
            getbackPath=jsonMap['data']['backPath'];
          });
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });
  }
  //获取人脸识别链接
  void getUrlAction(Map userMap)async{
    String? token =await TokenManager.getToken();
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header+'api/auth/faceOcr/user/faceUrl',
      data: {
        "id_no":dataList[1],
        "id_name":dataList[0],
        "certificate_type":0,
        "start_date":dataList[3].replaceAll("-", ""),
        "end_date":dataList[4].replaceAll("-", ""),
      },
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() async {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        if (code == "200") {
          BrnToast.show("提交成功", context,);
          setState(() {
            faceUrl=jsonMap['data']['url'];
            verufyToken=jsonMap['data']['verifyToken'];
          });
          String? uid = await UserIdManager.getUserID();
          String successUrl = "http://192.168.3.9:8080/pages/success/success?token=$verufyToken&uid=$uid&type=1";
          String encodedSuccessUrl = Uri.encodeComponent(successUrl);
          String faildHeadUrl =  "http://192.168.3.9:8080/pages/failed/failed";
          String encodedFaildHeadUrl = Uri.encodeComponent(
              faildHeadUrl);
          Navigator.push( context, FadeRoute(page:FaceCheckView(
            url: faceUrl + "&successUrl=" + encodedSuccessUrl + "&failedUrl=" + encodedFaildHeadUrl,type: 2, userMap: userMap,)));

        }else{
          BrnToast.show("身份信息有误，请核验后进行提交", context,);
        }
      });
    }).catchError((error) {
      print(error);
      ;
    });


  }
  String imageToBase64(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    String base64String = base64Encode(Uint8List.fromList(imageBytes));
    return base64String;
  }


  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);

    oneCheck==1?
    cardImgStr =base64String
        :cardImgStr2 =base64String;
    oneCheck==1?
    uploadOcrAction():uploadBackOcrAction();

  }


  //日期的校验
  bool isDateEarlierAndDifferenceGreaterThanFiveYears(String date1, String date2) {
    // 定义一个日期格式
    final dateFormat = DateFormat('yyyy-MM-dd');

    // 尝试解析第一个日期
    DateTime? firstDate;
    try {
      firstDate = dateFormat.parseStrict(date1);
    } catch (e) {
      // 如果解析失败，打印错误并返回false
      print('第一个日期格式不正确: $e');
      return false;
    }

    // 检查第二个日期是否为特殊情况
    if (date2 == '长期') {
      // 如果是“长期”，则只需确保第一个日期有效即可
      return true;
    }

    // 尝试解析第二个日期
    DateTime? secondDate;
    try {
      secondDate = dateFormat.parseStrict(date2);
    } catch (e) {
      // 如果解析失败，转为0000-00-00并认为是有效的
      print('第二个日期格式不正确，已转为默认值0000-00-00: $e');
      secondDate = DateTime(0, 0, 0); // 代表特殊值
    }

    // 检查第一个日期是否早于第二个日期
    if (firstDate.isAfter(secondDate)) {
      print('第一个日期必须早于第二个日期。');
      return false;
    }

    // 计算两个日期之间的差值
    final difference = secondDate.difference(firstDate).inDays / 365.25;

    // 检查日期差是否大于5年，注意对于0000-00-00我们已经通过了
    if (difference <= 5 && secondDate != DateTime(0, 0, 0)) {
      print('两个日期之间的间隔必须大于5年。');
      return false;
    }

    // 如果所有检查都通过了
    return true;
  }

  @override
  Widget build(BuildContext context) {
    var messages = AppLocalizations.of(context)!;
    final screenSize = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor:Color.fromRGBO(248, 248, 248, 1),
      appBar: AppBar(
        title: Text("司机认证",style: TextStyle(fontWeight: FontWeight.w300),),
        centerTitle: true,
        backgroundColor: Colors.white,
      ),
      body:Column(
        children: [
          Expanded(child:
          ListView(
            children: [
              SizedBox(height: 2,),
              SizedBox(height: 20,child: Container(color: Colors.white,),),
              Container(
                color: Colors.white,
                height:40.h,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("个人信息",style: TextStyle(fontSize: 12.sp,color: Color.fromRGBO(231, 112, 27, 0.85)),),
                        Text("①",style: TextStyle(fontSize: 12.sp,color: Color.fromRGBO(231, 112, 27, 0.85)),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("123123",style: TextStyle(fontSize: 12.sp,color: Colors.white,)),
                        Text("------",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("驾照信息",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                        Text("②",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("123123",style: TextStyle(fontSize: 12.sp,color: Colors.white,)),
                        Text("------",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("车辆信息",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                        Text("③",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("123123",style: TextStyle(fontSize: 12.sp,color: Colors.white,)),
                        Text("------",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text("资质信息",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                        Text("④",style: TextStyle(fontSize: 12.sp,color: Colors.black),),
                      ],
                    ),
                  ],
                ),
              ),
              SizedBox(height: 8.h,),
              Container(
                color: Colors.white,
                height: 140.h,
                child:Column(
                  // crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    SizedBox(height: 8.h,),
                    Row(
                      children: [
                        SizedBox(width: 18.w,),
                        Text("上传本人身份证(必填)",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                      ],
                    ),

                    SizedBox(height: 8.h,),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,

                      children: [

                        GestureDetector(
                          child:
                          _userImage!=null?
                          Stack(

                            children: [

                              Container(
                                height: 90.h,
                                width: 150.w,

                                child: Image.file(_userImage!) ,
                              ),
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          ):
                          getfrontPath!=""?
                          Stack(
                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child:   Image.network(MyServiceUrl.imgHeader+getfrontPath ,height: 90.h,width: 150.w,),
                              ),
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )

                              :
                          Image.asset("lib/Images/Authentication/身份证人像页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            showModalBottomSheet(context: context, builder: (BuildContext context) {
                              return Container(
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.all(Radius.circular(10))),
                                child:


                                Column(
                                  mainAxisSize: MainAxisSize.min,
                                  mainAxisAlignment:MainAxisAlignment.center,

                                  children:[
                                    Row(
                                      mainAxisAlignment:MainAxisAlignment.end,
                                      children: [
                                        IconButton(onPressed: (){
                                          Navigator.of(context).pop();
                                        }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                                      ],
                                    ),
                                    Text(messages["示例"],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                    SizedBox(height: 8.h,),
                                    Image.asset('lib/Images/Authentication/身份证人像页示例图.png',width: 2270.w,height: 145.h,),

                                    SizedBox(height: 8.h,),
                                    Text(messages["请按照示例上传"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),

                                    Text(messages["模糊、遮挡会导致证件无法识别，认证不通过"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                    SizedBox(height: 8.h,),
                                    Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                    SizedBox(height: 10.h,),
                                    Row(
                                      children: [
                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child:   Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                            Navigator.of(context).pop();
                                            final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                                            if (pickedFile != null) {

                                              setState(() {
                                                oneCheck=1;
                                                _userImage = File(pickedFile.path);
                                                printImageMemorySize(_userImage!);
                                                print(_userImage);
                                                compressImage(_userImage!);

                                              });
                                            }
                                          },
                                        ),

                                        SizedBox(width: 38.w,),
                                        GestureDetector(
                                          child: Column(
                                            children: [
                                              Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                              Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                            ],

                                          ),
                                          onTap: ()async{
                                            Navigator.of(context).pop();
                                            final pickedFile = await picker.pickImage(source: ImageSource.camera);

                                            if (pickedFile != null) {

                                              setState(() {
                                                oneCheck=1;
                                                _userImage = File(pickedFile.path);
                                                printImageMemorySize(_userImage!);
                                                print(_userImage);
                                                compressImage(_userImage!);

                                              });
                                            }
                                          },
                                        ),

                                      ],
                                    ),
                                    SizedBox(height: 30.h,),
                                  ],

                                ),

                              );


                            });

                          },
                        ),
                        SizedBox(width: 20.w,),
                        GestureDetector(
                          child:
                          _userImage2!=null?
                          Stack(

                            children: [

                              Container(
                                height: 90.h,
                                width: 150.w,

                                child: Image.file(_userImage2!) ,
                              ),
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          ):
                          getbackPath!=""?
                          Stack(
                            children: [
                              Container(
                                height: 90.h,
                                width: 150.w,
                                child:   Image.network(MyServiceUrl.imgHeader+getbackPath ,height: 90.h,width: 150.w,),
                              ),
                              Center(
                                child: Image.asset("lib/Images/Authentication/重新上传.png" ,height: 20.h,width: 50.w,),
                              ),
                            ],
                            alignment: Alignment.center,
                          )

                              :
                          Image.asset("lib/Images/Authentication/上传身份证国徽页.png" ,height: 90.h,width: 150.w,),
                          onTap: () async{
                            showModalBottomSheet(context: context, builder: (BuildContext context) {
                              return Container(
                                decoration: BoxDecoration(
                                    color: Colors.white,
                                    borderRadius: BorderRadius.all(Radius.circular(10))),
                                child:
                                Stack(

                                  children: [

                                    Column(
                                      mainAxisSize: MainAxisSize.min,
                                      mainAxisAlignment:MainAxisAlignment.center,

                                      children:[


                                        Row(
                                          mainAxisAlignment:MainAxisAlignment.end,
                                          children: [
                                            IconButton(onPressed: (){
                                              Navigator.of(context).pop();
                                            }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                                          ],
                                        ),
                                        Text(messages["示例"],style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                                        SizedBox(height: 8.h,),
                                        Image.asset('lib/Images/Authentication/上传身份证国徽页示例图.png',width: 2270.w,height: 145.h,),


                                        SizedBox(height: 8.h,),
                                        Text(messages["请按照示例上传"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                        Text(messages["模糊、遮挡会导致证件无法识别，认证不通过"],style: TextStyle(color: Color.fromRGBO(102, 102, 102, 1)),),
                                        SizedBox(height: 8.h,),
                                        Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                        SizedBox(height: 10.h,),
                                        Row(
                                          children: [
                                            SizedBox(width: 38.w,),
                                            GestureDetector(
                                              child:   Column(
                                                children: [
                                                  Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                                  Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                                ],

                                              ),
                                              onTap: ()async{
                                                Navigator.of(context).pop();
                                                final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                                                if (pickedFile != null) {
                                                  setState(() {
                                                    oneCheck=2;
                                                    _userImage2 = File(pickedFile.path);
                                                    printImageMemorySize(_userImage2!);
                                                    print(_userImage2);
                                                    compressImage(_userImage2!);

                                                  });
                                                }
                                              },
                                            ),

                                            SizedBox(width: 38.w,),
                                            GestureDetector(
                                              child: Column(
                                                children: [
                                                  Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                                  Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                                ],

                                              ),
                                              onTap: ()async{
                                                Navigator.of(context).pop();
                                                final pickedFile = await picker.pickImage(source: ImageSource.camera);

                                                if (pickedFile != null) {

                                                  setState(() {
                                                    oneCheck=2;
                                                    _userImage2 = File(pickedFile.path);
                                                    printImageMemorySize(_userImage2!);
                                                    print(_userImage2);
                                                    compressImage(_userImage2!);

                                                  });
                                                }
                                              },
                                            ),

                                          ],
                                        ),
                                        SizedBox(height: 30.h,),
                                      ],

                                    ),

                                  ],

                                ),
                              );


                            });

                          },
                        ),

                      ],
                    ),




                  ],
                ) ,
              ),
              SizedBox(height: 8.h,),
              Container(
                margin: EdgeInsets.only(left: 8.w,right: 8.w),
                height: 250.h,
                child:  ListView.separated(
                    physics: NeverScrollableScrollPhysics(),
                    itemCount:5,
                    separatorBuilder: (BuildContext context, int index) {
                      return Container(  // 这里使用 Divider 作为分隔符
                        color: Color.fromRGBO(248, 248, 248, 1),
                        height: 8.h,  // 分隔符的高度
                      );
                    },
                    itemBuilder:(context, index) {
                      return Padding(padding:

                      EdgeInsets.only(left: 8.w,right: 8.w),
                        child:  GestureDetector(
                            child:   Container(height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.white,
                                  borderRadius: BorderRadius.all(Radius.circular(10))),
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    children: [
                                      SizedBox(width: 8.h,),
                                      Text(titleList[index],style: TextStyle(color: Colors.black,fontSize: 14.sp ),),


                                    ],
                                  ),
                                  Row(
                                    children: [
                                      Container(
                                        width: screenSize.width-180.w,
                                        child: Text(dataList[index],textAlign: TextAlign.right,style: TextStyle(color:Colors.black,overflow:TextOverflow.ellipsis ,fontSize: 14.sp),),
                                      ),

                                      Icon(Icons.arrow_forward_ios,color: MyColors.authTipColor,size: 20,),
                                    ],
                                  ),



                                ],
                              ),
                            ),
                            onTap: () async{
                              if (index == 4) {
                                final result= await showModalBottomSheet(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return dataTimeSheet(
                                    );
                                  },
                                );

                                if (result != null) {
                                  String mounth="";
                                  String day="";

                                  setState(() {
                                    if(result[1].toString().length==1){
                                      mounth = result[1].toString().padLeft(2, '0');
                                    }else{
                                      mounth =result[1].toStringAsFixed(0);
                                    }
                                    if(result[2].toString().length==1){
                                      day = result[2].toString().padLeft(2, '0');
                                    }else{
                                      day =result[2].toStringAsFixed(0);
                                    }

                                    endTime=result[0].toString()+"-"+mounth+"-"+day;
                                    dataList[4]=endTime;
                                    print(endTime);
                                  });
                                }
                              }else   if (index == 3) {
                                final result= await showModalBottomSheet(
                                  context: context,
                                  builder: (BuildContext context) {
                                    return dataTimeSheet(
                                    );
                                  },
                                );

                                if (result != null) {
                                  String mounth="";
                                  String day="";

                                  setState(() {
                                    if(result[1].toString().length==1){
                                      mounth = result[1].toString().padLeft(2, '0');
                                    }else{
                                      mounth =result[1].toStringAsFixed(0);
                                    }
                                    if(result[2].toString().length==1){
                                      day = result[2].toString().padLeft(2, '0');
                                    }else{
                                      day =result[2].toStringAsFixed(0);
                                    }

                                    endTime=result[0].toString()+"-"+mounth+"-"+day;
                                    dataList[3]=endTime;
                                    print(endTime);
                                  });
                                }

                              } else {
                                _nametextEditingController.text =
                                dataList[index];
                                showModalBottomSheet(
                                    isDismissible: false,
                                    context: context,

                                    builder: (BuildContext context) {
                                      return Container(

                                        decoration: BoxDecoration(
                                            color: Colors.white,
                                            borderRadius: BorderRadius.all(Radius.circular(10))),
                                        child: Column(

                                          children: [

                                            SizedBox(height: 8.h,),
                                            Row(
                                              mainAxisAlignment: MainAxisAlignment
                                                  .spaceBetween,
                                              children: [
                                                TextButton(onPressed: () {
                                                  Navigator.of(context)
                                                      .pop();
                                                  setState(() {
                                                    if (index == 0) {
                                                      name = dataList[index];
                                                    } else
                                                    if (index == 1) {
                                                      IDCard =
                                                      dataList[index];
                                                    } else
                                                    if (index == 2) {
                                                      address =
                                                      dataList[index];
                                                    }

                                                    _nametextEditingController
                                                        .text =
                                                    dataList[index];
                                                  });
                                                },
                                                    child: Text(
                                                      messages["取消"],
                                                      style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
                                                Text(titleList[index] +
                                                    "输入",
                                                  style: TextStyle(
                                                      color: Colors.black,
                                                      fontSize: 16.sp,
                                                      fontWeight: FontWeight
                                                          .w600),),
                                                TextButton(onPressed: () {
                                                  Navigator.of(context)
                                                      .pop();

                                                  setState(() {
                                                    if (index == 0) {
                                                      dataList[index] =
                                                          name;
                                                    } else
                                                    if (index == 1) {
                                                      dataList[index] =
                                                          IDCard;
                                                    } else
                                                    if (index == 2) {
                                                      dataList[index] =
                                                          address;
                                                    }

                                                    _nametextEditingController
                                                        .text =
                                                    dataList[index];
                                                  });
                                                },
                                                  child: Text(
                                                    messages["确定"],
                                                    style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 14.sp),),),
                                              ],
                                            ),
                                            SizedBox(height: 8.h,),
                                            Container(

                                              margin: EdgeInsets.only(
                                                  left: 18.w,
                                                  right: 18.w),
                                              decoration: BoxDecoration(
                                                borderRadius: BorderRadius
                                                    .circular(30.0),

                                              ),
                                              child: TextField(
                                                // keyboardType: TextInputType.number,
                                                  controller: _nametextEditingController,

                                                  style: TextStyle(
                                                    color: Colors.black,
                                                  ),
                                                  decoration: InputDecoration(
                                                    filled: true,
                                                    fillColor: Color
                                                        .fromRGBO(
                                                        249, 249, 249, 1),
                                                    border: InputBorder
                                                        .none,


                                                  ),
                                                  onChanged: (text) {
                                                    setState(() {
                                                      if (index == 0) {
                                                        name = text;

                                                      } else
                                                      if (index == 1) {
                                                        IDCard = text;
                                                      } else
                                                      if (index == 2) {
                                                        address = text;
                                                      }

                                                    });
                                                  }
                                              ),
                                            ),

                                          ],
                                        ),
                                      );
                                    });
                              }
                            }
                        ),
                      );
                    }
                ),
              ),
              SizedBox(height: 8.h,),
              Padding(padding:  EdgeInsets.only(left: 8.w,right: 8.w),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: [
                    Row(
                      children: [

                        Text("请保持身份证照片与文本信息一致后提交审核",style: TextStyle(color: Color.fromRGBO(231, 112, 27, 0.85),fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      ],
                    ),
                    SizedBox(height: 8.h,),
                    Text("为保障交易安全，履行实名制认证的法律规定，请根据页面提示输入真实姓名、身份证号以及住址或上传身份证照片。请注意，身份证照片即身份证号均属敏感个人信息。实名信息一旦认证，无法随意更改，请谨慎填写。",
                      style: TextStyle(color: MyColors.authTipColor),),
                  ],
                ),
              ),
              Padding(padding:

              EdgeInsets.only(left: 8.w,right: 8.w),
                child: Container(
                  height: 100.h,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage("lib/Images/Authentication/党员身份选择.png"),
                    ),
                  ),
                  child: Column(
                    children: [
                      SizedBox(height: 50.h,),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          // SizedBox(
                          //   width: 10.w,
                          // ),
                          Text("   身份",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 14.sp),),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.end,
                            children: [IconButton(
                              onPressed: () => {
                                setState(() {

                                  ChooseIndex = "1";

                                })
                              },
                              icon:ChooseIndex != "1" ? Icon(Icons.radio_button_unchecked): Icon(Icons.radio_button_checked),
                              color: ChooseIndex == "1" ? Colors.orange : Colors.grey,
                            ),
                              Text("党员",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                              IconButton(
                                onPressed: () => {
                                  setState(() {

                                    ChooseIndex = "2";

                                  })
                                },
                                icon:ChooseIndex != "2" ? Icon(Icons.radio_button_unchecked): Icon(Icons.radio_button_checked),
                                color: ChooseIndex == "2" ? Colors.orange : Colors.grey,
                              ),
                              Text("团员",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                              IconButton(
                                onPressed: () => {
                                  setState(() {

                                    ChooseIndex = "3";

                                  })
                                },
                                icon:ChooseIndex != "3" ? Icon(Icons.radio_button_unchecked): Icon(Icons.radio_button_checked),
                                color: ChooseIndex == "3" ? Colors.orange : Colors.grey,
                              ),
                              Text("其他   ",style: TextStyle(color: Colors.black,fontSize: 14.sp),),],

                          ),

                        ],
                      ),

                    ],
                  ),
                ),




              ),

            ],
          ),
          ),
          Container(
            height: 80.h,
            color: Colors.white,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                    height: 40.h ,
                    margin: EdgeInsets.only(left: 30.w,right: 30.w),
                    decoration: BoxDecoration(
                        color:MyColors.themeColor,
                        borderRadius: BorderRadius.all(Radius.circular(30))),

                    width: double.infinity,


                    child: TextButton(
                      child: Text("下一步",style: TextStyle(color: Colors.white,fontSize: 14.sp,fontWeight: FontWeight.w600),),

                      onPressed: ()async{
                        if(dataList[0]=="") {
                          BrnToast.show("请填写姓名", context,);
                        }else if(dataList[1]==""){
                          BrnToast.show("请填写身份证号码", context,);
                        }else if(dataList[2]==""){
                          BrnToast.show("请填写住址", context,);
                        }else if(dataList[3]==""){
                          BrnToast.show("请选择起始时间", context,);
                        }else if(dataList[4]==""){
                          BrnToast.show("请选择到期时间", context,);
                        }else if(getfrontPath==""||getbackPath==""){
                          BrnToast.show("请添加身份证图片", context,);
                        }else if(!isDateEarlierAndDifferenceGreaterThanFiveYears(dataList[3], dataList[4])){
                          BrnToast.show("起始时间或到期时间不正确", context,);
                        }else{
                          String? drvId =await UserIdManager.getUserID();
                          String? phoneNum =await PhoneNumManager.getPhone();
                          ApiManager.postData(
                            context,
                            'api/auth/driver/user/editPersonalInfo',
                            {
                              "id": drvId,
                              "phoneNum": phoneNum,
                              "realName": dataList[0],
                              "idNum": dataList[1],
                              "address": dataList[2],
                              "validFrom": dataList[3],
                              "validTo": dataList[4],
                              "frontPath":getfrontPath,
                              "backPath":getbackPath,
                              "authStatus": 0,
                              "status": 0,
                              "identity":ChooseIndex=="1"?"PARTY":ChooseIndex=="2"?"TEAM":"OTHER",
                              "faceSuccess":0
                            },
                                (responseData) async {
                                  BrnToast.show("提交成功", context,);
                                  // if(responseData['needFace']=true){

                                    setState(() {
                                      faceUrl=responseData['data']['faceUrl'];
                                      verufyToken=responseData['data']['verifyToken'];
                                    });
                                    String? uid = await UserIdManager.getUserID();
                                    String? phoneNum = await PhoneNumManager.getPhone();
                                    String successUrl = "http://192.168.3.9:8082/pages/success/success?token=$verufyToken&uid=$uid&type=1";
                                    String encodedSuccessUrl = Uri.encodeComponent(successUrl);
                                    String faildHeadUrl =  "http://192.168.3.9:8082/pages/failed/failed";
                                    String encodedFaildHeadUrl = Uri.encodeComponent(
                                        faildHeadUrl);

                          Navigator.push( context, FadeRoute(page:FaceCheckView(
                                            url: faceUrl + "&successUrl=" + encodedSuccessUrl + "&failedUrl=" + encodedFaildHeadUrl, type: 1, userMap: {
                                    "id": drvId,
                                    "phoneNum": phoneNum,
                                    "realName": dataList[0],
                                    "idNum": dataList[1],
                                    "address": dataList[2],
                                    "validFrom": dataList[3],
                                    "validTo": dataList[4],
                                    "frontPath":getfrontPath,
                                    "backPath":getbackPath,
                                    "authStatus": 0,
                                    "status": 0,
                                    "identity":ChooseIndex=="1"?"PARTY":ChooseIndex=="2"?"TEAM":"OTHER",
                                    "faceSuccess":0
                                    })
                                        ));


                            },
                          );

                        }

                      },


                    )
                ),
              ],
            ),
          ),



          // }),
        ],
      ),

    );
  }
}


